<template>
    <div class="finance-handle-show">

      <!-- 筛选区 -->
      <el-card class="filter-card" style="margin-bottom: 20px;">
        <el-form :inline="true" :model="filters" class="filter-form">
          <el-form-item label="流水号">
            <el-input v-model="filters.serialNo" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="名称">
            <el-input v-model="filters.name" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="财务类别">
            <el-select v-model="filters.category" placeholder="请选择" style="width: 160px">
              <el-option label="请选择" value="" />
              <el-option label="微信" value="微信" />
               <el-option label="支付宝" value="支付宝" />
                <el-option label="建设银行" value="建设银行" />
              <!-- 其他选项 -->
            </el-select>
          </el-form-item>
          <el-form-item :label="type === 1 ? '付款方' : '收款方'">
            <el-input v-model="filters.payer" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="起始时间">
            <el-date-picker 
              v-model="filters.StartTime" 
              type="date" 
              placeholder="开始时间"
              value-format="YYYY-MM-DD"
              format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item label="结束时间">
            <el-date-picker 
              v-model="filters.EndTime" 
              type="date" 
              placeholder="结束时间"
              value-format="YYYY-MM-DD"
              format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="filters.status" placeholder="请选择" style="width: 160px">
              <el-option label="全部" value="" />
              <el-option label="待审核" value="待审核" />
              <el-option label="审核通过" value="审核通过" />
              <el-option label="部分付款" value="部分付款" />
              <el-option label="全部付款" value="全部付款" />
              <el-option label="审核失败" value="审核失败" />
            </el-select>
          </el-form-item>
          <el-form-item label="审核人">
            <el-input v-model="filters.auditor" placeholder="请输入" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSearch">查询</el-button>
            <el-button @click="onReset">重置</el-button>
            <el-button type="primary" @click="onAdd">添加</el-button>
          </el-form-item>
        </el-form>
      </el-card>
  
      <!-- 数据表格 -->
      <el-card class="table-card">
        <el-table
          :data="tableData"
          border
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="58" />
          <el-table-column prop="serialNumber" label="流水号" width="120" />
          <el-table-column prop="productName" label="名称" width="180" />
          <el-table-column prop="payMentType" label="分类" width="100" />
          <el-table-column :prop="type === 1 ? 'payer' : 'payee'" :label="type === 1 ? '付款方' : '收款方'" width="100" />
          <el-table-column prop="money" :label="type === 1 ? '应收金额' : '应付金额'" width="100" />
          <el-table-column prop="paymentAmount" :label="type === 1 ? '实收金额' : '实付金额'" width="100" />
          <el-table-column prop="balance" :label="type === 1 ? '剩余金额' : '剩余金额'" width="100" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              {{ scope.row.status === '通过' ? '审核成功' : scope.row.status }}
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="120">
            <template #default="scope">
              {{ formatDate(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="auditor" label="审核人" width="100">
         
          </el-table-column>
          <el-table-column label="操作" width="320">
            <template #default="scope">
              <el-button size="small" @click="onEdit(scope.row)">编辑</el-button>
              <el-button size="small" type="danger" @click="onDelete(scope.row.id)">删除</el-button>
              <el-button size="small" @click="onView(scope.row)">查看</el-button>
              <el-button size="small" type="primary" @click="onAudit(scope.row)">审核</el-button>
              <el-button size="small" type="success" @click="onReceive(scope.row)">{{ type === 1 ? '收款' : '付款' }}</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 批量操作和分页 -->
        <div class="table-footer">
          <el-pagination
            v-model:current-page="pagination.page"
            :page-size="pagination.pageSize"
            :total="pagination.totalCount"
            layout="total, prev, pager, next, jumper"
            @current-change="onPageChange"
          />
          <div class="footer-right">
            <el-button @click="onBatchDelete" :disabled="!multipleSelection.length">批量删除</el-button>
            <el-button @click="handleExport" style="margin-left: 8px;">导出</el-button>
          </div>
        </div>
      </el-card>
  
      <!-- 新增弹窗 -->
      <el-dialog v-model="addDialogVisible" :title="type === 1 ? '新增应收' : '新增应付'" width="700px">
        <el-form :model="addForm" label-width="100px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="流水号">
                <el-input v-model="addForm.serialNumber" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="名称">
                <el-input v-model="addForm.productName" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="类别">
                <el-select v-model="addForm.payMentType" placeholder="请选择">
                  <el-option label="微信" value="微信" />
                  <el-option label="支付宝" value="支付宝" />
                  <el-option label="建设银行" value="建设银行" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="最后付款日">
                <el-date-picker 
                  v-model="addForm.paymentDate" 
                  type="date" 
                  placeholder="请选择" 
                  style="width: 100%"
                  value-format="YYYY-MM-DD"
                  format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item :label="type === 1 ? '付款方' : '收款方'">
                <el-input v-model="addForm.payer" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="type === 1 ? '收款方' : '付款方'">
                <el-input v-model="addForm.payee" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item :label="type === 1 ? '应收金额' : '应付金额'">
                <el-input v-model="addForm.money" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="付款次数">
                <el-input v-model="addForm.paymentDegree" />
              </el-form-item>
            </el-col>
            
          </el-row>
          <el-form-item label="备注">
            <el-input v-model="addForm.note" type="textarea" rows="3" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="onAddConfirm">确定</el-button>
        </template>
      </el-dialog>

      <!-- 查看详情弹窗 -->
      <el-dialog v-model="viewDialogVisible" title="详情" width="700px">
        <div class="detail-content">
          <div class="detail-row">
            <div class="detail-item">
              <span class="label">流水号：</span>
              <span class="value">{{ viewForm.serialNumber }}</span>
            </div>
            <div class="detail-item">
              <span class="label">名称：</span>
              <span class="value">{{ viewForm.productName }}</span>
            </div>
          </div>
          <div class="detail-row">
            <div class="detail-item">
              <span class="label">类别：</span>
              <span class="value">{{ viewForm.payMentType }}</span>
            </div>
            <div class="detail-item">
              <span class="label">最后付款日：</span>
              <span class="value">{{ viewForm.paymentDate }}</span>
            </div>
          </div>
          <div class="detail-row">
            <div class="detail-item">
              <span class="label">{{ type === 1 ? '付款方：' : '收款方：' }}</span>
              <span class="value">{{ viewForm.payer }}</span>
            </div>
            <div class="detail-item">
              <span class="label">{{ type === 1 ? '收款方：' : '付款方：' }}</span>
              <span class="value">{{ viewForm.payee }}</span>
            </div>
          </div>
          <div class="detail-row">
            <div class="detail-item">
              <span class="label">{{ type === 1 ? '应收金额：' : '应付金额：' }}</span>
              <span class="value">{{ viewForm.money }}</span>
            </div>
            <div class="detail-item">
              <span class="label">付款次数：</span>
              <span class="value">{{ viewForm.paymentDegree }}</span>
            </div>
          </div>
          <div class="detail-row">
            <div class="detail-item">
              <span class="label">审核人：</span>
              <span class="value">{{ viewForm.auditor }}</span>
            </div>
          </div>
        </div>
        <template #footer>
          <el-button @click="viewDialogVisible = false">关闭</el-button>
        </template>
      </el-dialog>

      <!-- 编辑弹窗 -->
      <el-dialog v-model="editDialogVisible" title="编辑" width="700px">
        <el-form :model="editForm" label-width="100px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="流水号">
                <el-input v-model="editForm.serialNumber" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="名称">
                <el-input v-model="editForm.productName" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="类别">
                <el-select v-model="editForm.payMentType" placeholder="请选择" style="width: 100%">
                  <el-option label="微信" value="微信" />
                  <el-option label="支付宝" value="支付宝" />
                  <el-option label="建设银行" value="建设银行" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="最后付款日">
                <el-date-picker 
                  v-model="editForm.paymentDate" 
                  type="date" 
                  placeholder="请选择" 
                  style="width: 100%"
                  value-format="YYYY-MM-DD"
                  format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item :label="type === 1 ? '付款方' : '收款方'">
                <el-input v-model="editForm.payer" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="type === 1 ? '收款方' : '付款方'">
                <el-input v-model="editForm.payee" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item :label="type === 1 ? '应收金额' : '应付金额'">
                <el-input v-model="editForm.money" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="付款次数">
                <el-input v-model="editForm.paymentDegree" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="审核人">
                <el-input v-model="editForm.auditor" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="onEditConfirm">确定</el-button>
        </template>
      </el-dialog>

      <!-- 审核弹窗 -->
      <el-dialog v-model="auditDialogVisible" :title="type === 1 ? '应收审批' : '应付审批'" width="700px">
        <el-form :model="auditForm" label-width="100px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="流水号">
                <el-input v-model="auditForm.serialNumber" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="名称">
                <el-input v-model="auditForm.productName" readonly />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="类别">
                <el-input v-model="auditForm.payMentType" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="最后付款日">
                <el-input v-model="auditForm.paymentDate" readonly />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item :label="type === 1 ? '付款方' : '收款方'">
                <el-input v-model="auditForm.payer" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="type === 1 ? '收款方' : '付款方'">
                <el-input v-model="auditForm.payee" readonly />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item :label="type === 1 ? '应收金额' : '应付金额'">
                <el-input v-model="auditForm.money" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="付款次数">
                <el-input v-model="auditForm.paymentDegree" readonly />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="审核原因">
            <el-input v-model="auditForm.reason" type="textarea" rows="3" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="auditDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="() => onAuditConfirm('通过')">审核通过</el-button>
          <el-button type="danger" @click="() => onAuditConfirm('不通过')">审核不通过</el-button>
        </template>
      </el-dialog>

      <!-- 收款弹窗 -->
      <el-dialog v-model="receiveDialogVisible" :title="type === 1 ? '新增实收' : '新增实付'" width="700px">
        <el-form :model="receiveForm" label-width="100px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="流水号">
                <el-input v-model="receiveForm.serialNumber" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="名称">
                <el-input v-model="receiveForm.productName" readonly />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="类别">
                <el-select v-model="receiveForm.payMentType" placeholder="请选择" style="width: 100%">
                  <el-option label="微信" value="微信" />
                  <el-option label="支付宝" value="支付宝" />
                  <el-option label="建设银行" value="建设银行" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="最后付款日">
                <el-date-picker 
                  v-model="receiveForm.paymentDate" 
                  type="date" 
                  placeholder="请选择" 
                  style="width: 100%"
                  value-format="YYYY-MM-DD"
                  format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item :label="type === 1 ? '付款方' : '收款方'">
                <el-input v-model="receiveForm.payer" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="type === 1 ? '收款方' : '付款方'">
                <el-input v-model="receiveForm.payee" readonly />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item :label="type === 1 ? '应收金额' : '应付金额'">
                <el-input v-model="receiveForm.money" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="付款次数">
                <el-input v-model="receiveForm.paymentDegree" readonly />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="付款机构">
                <el-input v-model="receiveForm.paymentInstitution" placeholder="请输入付款机构" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="type === 1 ? '收款金额' : '付款金额'">
                <el-input v-model="receiveForm.paymentAmount" placeholder="请输入金额" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="备注">
            <el-input v-model="receiveForm.note" type="textarea" rows="3" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="receiveDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="onReceiveConfirm">确定</el-button>
        </template>
      </el-dialog>

    </div>
  </template>
  
  <script setup>
  import { ref, reactive, onMounted, computed } from 'vue'
  import { useRoute } from 'vue-router'
  import { FinanceRed, FinanceWrite } from '@/http/axiosHelper'
  import { ElMessage,ElMessageBox,ElNotification } from 'element-plus'
    import { statementRed } from '@/http/axiosHelper'
  // 获取路由参数
  const route = useRoute()
  
  // 根据路由参数或查询参数获取type，默认为1（应收）
  const type = computed(() => {
    const routeType = route.params.type || route.query.type
    return routeType ? parseInt(routeType) : 1
  })
  
  // 根据type计算页面标题
  const pageTitle = computed(() => {
    return type.value === 1 ? '应收管理' : '应付管理'
  })
  
  function formatDate(dateStr) {
    if (!dateStr) return ''
    return dateStr.replace('T', ' ').replace(/\.\d+Z?$/, '')
  }
  
  const filters = reactive({
    serialNo: '',
    name: '',
    category: '',
    payer: '',
    StartTime: '',
    EndTime: '',
    status: '',
    auditor: '',
    type: computed(() => type.value), // 动态设置type
  })
  
  const tableData = ref([

  ])
  
  const multipleSelection = ref([])
  const pagination = reactive({
    page: 1,
    pageSize: 10,
    totalCount: 20
  })
//添加的表单
  const addDialogVisible = ref(false)
  const addForm = reactive({
    serialNumber: '',
    productName: '',
    payMentType: '',
    paymentDate: '',
    payer: '',
    payee: '',
    money: '',
    paymentDegree: '',
    note: '',
    auditor:"王雨龙"
  })
  // 格式化日期为字符串
  function formatDateForAPI(date) {
    if (!date) return ''
    // 由于设置了 value-format="YYYY-MM-DD"，直接返回即可
    return date
  }

  //显示的方法
  function fetchReceivableList() {
    const params = {
      pageIndex: pagination.page,
      pageSize: pagination.pageSize,
      serialNumber: filters.serialNo,
      productName: filters.name,
      payMentType: filters.category,
      payer: filters.payer,
      status: filters.status,
      auditor: filters.auditor,
      type: type.value // 传递type参数
    }
    
    // 添加时间参数
    const StartTime = formatDateForAPI(filters.StartTime)
    const EndTime = formatDateForAPI(filters.EndTime)
    
    if (StartTime) {
      params.StartTime = StartTime
    }
    
    if (EndTime) {
      params.EndTime = EndTime
    }
    
    FinanceRed.get('/api/Management/GetManagement', { params })
      .then(res => {
        if (res.data.code === 200) {
          console.log(res.data.data);
          
          tableData.value = res.data.data || []
          pagination.totalCount = res.data.totalCount || 0
        } else {
          ElMessage.error(res.data.msg || '查询失败')
        }
      })
      .catch(err => {
        ElMessage.error('查询失败：' + (err?.message || '网络或服务器异常'))
      })
  }
//生命周期
  onMounted(() => {
    fetchReceivableList()
  })

  function onSearch() {
    pagination.page = 1
    fetchReceivableList()
  }
  function onReset() {
    Object.assign(filters, {
      serialNo: '',
      name: '',
      category: '',
      payer: '',
      StartTime: null,
      EndTime: null,
      status: '',
      auditor: ''
    })
    // 重置后立即查询
    pagination.page = 1
    fetchReceivableList()
  }
  function handleSelectionChange(val) {
    multipleSelection.value = val
  }
  function onEdit(row) {
    editDialogVisible.value = true
    Object.assign(editForm, row)
  }
  // 单删除逻辑
  function onDelete(id)
  {
    ElMessageBox.confirm(
    '该操作将删除该数据, 确定要删除吗?',
    '确认提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      // 用户点击确定，调用后端删除接口
      FinanceWrite.delete("/api/Management/DelManagement", { data: { id: id } })
        .then(res => {
          if (res.data.code === 200) {
            ElNotification({
              title: '数据删除成功',
              message: '数据删除成功',
              type: 'success',
              position: 'bottom-right'
            });
            fetchReceivableList(); // 刷新表格
          } else {
            ElNotification({
              title: '删除失败',
              message: res.data.msg || '删除操作未成功',
              type: 'error',
              position: 'bottom-right'
            });
          }
        })
        .catch(() => {
          ElNotification({
            title: '删除失败',
            message: '删除操作未成功',
            type: 'error',
            position: 'bottom-right'
          });
        });
    })
    .catch(() => {
      // 用户点击取消，无需操作
    });
  }
  function onView(row) {
    viewDialogVisible.value = true
    Object.assign(viewForm, row)
  }
  const auditDialogVisible = ref(false)
  const auditForm = reactive({
    id: '',
    serialNumber: '',
    productName: '',
    payMentType: '',
    paymentDate: '',
    payer: '',
    payee: '',
    money: '',
    paymentDegree: '',
    reason: ''
  })
  function onAudit(row) {
    auditDialogVisible.value = true
    Object.assign(auditForm, {
      ...row,
      reason: ''
    })
  }
  function onAuditConfirm(status) {
    // status: '通过' or '不通过'
    const payload = {
      id: auditForm.id,
      reason: auditForm.reason,
      status: status, // 直接传递'通过'或'不通过'
      operation_Type: 2
    }
    FinanceWrite.put('/api/Management/Audit', payload)
      .then(res => {
        if (res.data.code === 200) {
          auditDialogVisible.value = false
          fetchReceivableList()
          ElMessage.success('审核' + status + '成功')
        } else {
          ElMessage.error(res.data.msg || '审核失败')
        }
      })
      .catch(err => {
        ElMessage.error('审核失败：' + (err?.message || '网络或服务器异常'))
      })
  }
  //批量删除
  function onBatchDelete() {
    if (!multipleSelection.value.length) {
      ElMessage.warning('请先选择要删除的数据')
      return
    }
    ElMessageBox.confirm(
      `确定要删除选中的${multipleSelection.value.length}条数据吗？`,
      '批量删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
      .then(() => {
        // 批量删除接口，假设后端支持批量删除
        const ids = multipleSelection.value.map(item => item.id)
        FinanceWrite.delete('/api/Management/BatchDeleteManagement', { data:{id:ids.join(',')} })
          .then(res => {
            if (res.data.code === 200) {
              ElNotification({
                title: '批量删除成功',
                message: '批量删除成功',
                type: 'success',
                position: 'bottom-right'
              });
              fetchReceivableList()
            } else {
              ElMessage.error(res.data.msg || '批量删除失败')
            }
          })
          .catch(() => {
            ElMessage.error('批量删除失败，网络或服务器异常')
          })
      })
      .catch(() => {
        // 用户取消，无需操作
      })
  }

    // 添加时间参数
    const StartTime = formatDateForAPI(filters.StartTime)
    const EndTime = formatDateForAPI(filters.EndTime)
    
    if (StartTime) {
      exportParams.StartTime = StartTime
    }
    
    if (EndTime) {
      exportParams.EndTime = EndTime
    }
    

  function onPageChange(page) {
    pagination.page = page
    fetchReceivableList()
  }
  //添加的方法
  function onAdd() {
    addDialogVisible.value = true
    // 生成8位随机数字
    const serial = Math.floor(10000000 + Math.random() * 90000000)
    Object.assign(addForm, {
      type: type.value, // 根据当前type设置
      sellId: 2,
      serialNumber: serial,
      productName: '',
      payMentType: '',
      paymentDate: '',
      payer: '',
      payee: '',
      money: '',
      paymentDegree: '',
      note: '',
      PaymentInstitution:''
    })
  }
  function onAddConfirm() {
    // 处理日期格式
    const submitData = {
      ...addForm,
      paymentDate: formatDateForAPI(addForm.paymentDate)
    }
    
    FinanceWrite.post('/api/Management/AddManagement', submitData)
      .then(res => {
        if (res.data.code === 200) {
          addDialogVisible.value = false
          fetchReceivableList()
          ElMessage.success('添加成功')
        } else {
          ElMessage.error(res.data.msg || '添加失败')
        }
      })
      .catch(err => {
        ElMessage.error('添加失败：' + (err?.message || '网络或服务器异常'))
      })
  }

  const viewDialogVisible = ref(false)
  const viewForm = reactive({
    serialNumber: '',
    productName: '',
    payMentType: '',
    paymentDate: '',
    payer: '',
    payee: '',
    money: '',
    paymentDegree: '',
    auditor: ''
  })

  const editDialogVisible = ref(false)
  const editForm = reactive({
    id: '',
    type:1,
    sellId:1,
    serialNumber: '',
    productName: '',
    payMentType: '',
    paymentDate: '',
    note:'',
    payer: '',
    payee: '',
    money: '',
    paymentDegree: '',
    auditor: '',
    paymentInstitution:'',
    paymentAmount:'',

  })

  // 收款相关变量和方法
  const receiveDialogVisible = ref(false)
  const receiveForm = reactive({
    id: '',
    type: 1,
    sellId: 1,
    serialNumber: '',
    productName: '',
    payMentType: '',
    paymentDate: '',
    payer: '',
    payee: '',
    money: '',
    paymentDegree: '',
    paymentInstitution: '',
    paymentAmount: '',
    note: ''
  })

  // 点击收款按钮
  function onReceive(row) {
    receiveDialogVisible.value = true
    Object.assign(receiveForm, {
      ...row,
      paymentInstitution: '', // 付款机构为空，需要手动填写
      paymentAmount: '', // 付款金额为空，需要手动填写
      note: ''
    })
  }

  // 收款确认
  function onReceiveConfirm() {
    // 验证必填字段
    if (!receiveForm.paymentInstitution) {
      ElMessage.warning('请输入付款机构')
      return
    }
    if (!receiveForm.paymentAmount) {
      ElMessage.warning('请输入付款金额')
      return
    }

    // 处理日期格式
    const submitData = {
      ...receiveForm,
      paymentDate: formatDateForAPI(receiveForm.paymentDate)
    }

    FinanceWrite.put('/api/Management/UpdateManagement', submitData)
      .then(res => {
        if (res.data.code === 200) {
          receiveDialogVisible.value = false
          fetchReceivableList()
          ElMessage.success(type.value === 1 ? '收款记录添加成功' : '付款记录添加成功')
        } else {
          ElMessage.error(res.data.msg || (type.value === 1 ? '收款记录添加失败' : '付款记录添加失败'))
        }
      })
      .catch(err => {
        ElMessage.error((type.value === 1 ? '收款记录添加失败：' : '付款记录添加失败：') + (err?.message || '网络或服务器异常'))
      })
  }
//编辑的方法
  function onEditConfirm() {
    // 处理日期格式
    const submitData = {
      ...editForm,
      paymentDate: formatDateForAPI(editForm.paymentDate)
    }
    
    FinanceWrite.put('/api/Management/UpdateManagement', submitData)
      .then(res => {
        if (res.data.code === 200) {
          editDialogVisible.value = false
          fetchReceivableList()
          ElMessage.success('修改成功')
        } else {
          ElMessage.error(res.data.msg || '修改失败')
        }
      })
      .catch(err => {
        ElMessage.error('修改失败：' + (err?.message || '网络或服务器异常'))
      })
  }

// 导出函数（假设已配置 Axios 拦截器自动添加 Token）
async function handleExport() {
  try {
    // 1. 组装参数
    const params = {
      pageIndex: pagination.page,
      pageSize: pagination.pageSize,
      type: type.value,
      productName: filters.name,
      payer: filters.payer,
      payMentType: filters.category,
      status: filters.status,
      auditor: filters.auditor,
      startTime: formatDateForAPI(filters.StartTime),
      endTime: formatDateForAPI(filters.EndTime),
    };

    // 2. 调用后端导出接口
    const response = await FinanceRed({
      url: '/api/Management/GetManagementExport',
      method: 'get',
      params,
      responseType: 'blob',
    });

    // 3. 获取文件名
    const fileName = getFileNameFromHeaders(response.headers);

    // 4. 下载文件
    const blob = new Blob([response.data], {
      type: response.headers['content-type'] || 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = fileName;
    document.body.appendChild(a);
    a.click();
    window.URL.revokeObjectURL(url);
    document.body.removeChild(a);

  } catch (error) {
    console.error('导出失败：', error.response?.data || error.message);
    alert('导出失败，请检查参数或重新登录');
  }
}

// 辅助函数
function getFileNameFromHeaders(headers) {
  const contentDisposition = headers['content-disposition'] || headers['Content-Disposition'];
  if (!contentDisposition) return '应收应付管理.xlsx';
  // filename*=UTF-8''xxx.xlsx 或 filename=xxx.xlsx
  let fileName = '应收应付管理.xlsx';
  const utf8Match = contentDisposition.match(/filename\*=UTF-8''([^;]+)/);
  if (utf8Match) {
    fileName = decodeURIComponent(utf8Match[1]);
  } else {
    const asciiMatch = contentDisposition.match(/filename="?([^"]+)"?/);
    if (asciiMatch) {
      fileName = decodeURIComponent(asciiMatch[1]);
    }
  }
  return fileName;
}







  </script>
  
  <style scoped>
  .finance-handle-show {
    padding: 20px;
    max-width: 1600px;
    margin: 0 auto;
  }
  .page-title {
    margin-bottom: 20px;
    text-align: center;
  }
  .page-title h2 {
    color: #333;
    font-size: 24px;
    font-weight: bold;
  }
  .filter-form {
    margin-bottom: 20px;
  }
  .table-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 10px;
  }
  .footer-right {
    display: flex;
    align-items: center;
    margin-left: auto;
  }
  
  .detail-content {
    padding: 20px;
  }
  
  .detail-row {
    display: flex;
    margin-bottom: 20px;
  }
  
  .detail-item {
    flex: 1;
    display: flex;
    align-items: center;
  }
  
  .detail-item .label {
    font-weight: bold;
    color: #606266;
    min-width: 100px;
    margin-right: 10px;
  }
  
  .detail-item .value {
    color: #333;
    flex: 1;
  }
  </style>